import java.io.IOException;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class UdpEchoClient {//客户端类
    private DatagramSocket socket=null;
    private String serverIP;//服务器IP
    private int serverPort;//服务器端口号
    public UdpEchoClient(String serverIP,int serverPort) throws SocketException {
        socket=new DatagramSocket();//客户端不用特意指定端口号,系统自动分配
        this.serverIP=serverIP;
        this.serverPort=serverPort;//给定服务器IP及端口
    }
    //启动客户端
    public void stack() throws IOException {
        System.out.println("客户端启动:");
        Scanner scanner=new Scanner(System.in);//请求从键盘中输入
        while (true){
            System.out.println("->");
            String request=scanner.next();//获取请求
            //把字符串构成udp数据报,并且进行发送
            DatagramPacket requestPacket=new DatagramPacket(request.getBytes(StandardCharsets.UTF_8),request.getBytes().length, InetAddress.getByName(serverIP),serverPort);
            socket.send(requestPacket);//发送请求到服务器
            //接收服务器的返回值
            DatagramPacket responsePacket=new DatagramPacket(new byte[4096],4096);
            socket.receive(responsePacket);//填满空盒子
            String response=new String(responsePacket.getData(),0,responsePacket.getLength());//把响应转化为字符串打印
            System.out.printf("req:%s,resp:%s",request,response);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient udpEchoClient=new UdpEchoClient("10.79.177.79",4090);
        udpEchoClient.stack();
    }
}
